import requests
from bs4 import BeautifulSoup
import re
import json


class GetBookInfo:

    header = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0"
    }

    def __init__(self, isbn):
        if isbn == "":
            self.isbn = "1234567890123"
        else:
            self.isbn = isbn

        self.bookinfo = {}
        self.init_info = None

    def getbookurl(self):

        url = "https://search.douban.com/book/subject_search?search_text=" + self.isbn
        r = requests.get(url, headers=self.header)

        info = re.findall("window.__DATA__ = (.*?);", r.text, re.S)[0]
        bookinfo_dic = json.loads(info)
        self.init_info = bookinfo_dic
        book_url = bookinfo_dic["items"][0]["url"]
        self.bookinfo["book_url"] = book_url
        # print(bookinfo_dic)

    def getbookinfo(self):
        """
        利用豆瓣API读取图书信息
        """
        self.getbookurl()
        book_url = self.bookinfo["book_url"]

        r = requests.get(book_url, headers=self.header)
        soup = BeautifulSoup(r.text, "lxml")

        book_name = soup.find(attrs={"property": "v:itemreviewed"}).string
        authors = [
            info.find(attrs={"class": "name"})
            for info in soup.find_all(attrs={"class": "author"})
        ]
        author = "/".join(
            self.init_info["items"][0]["abstract"].split("/")[0 : len(authors) - 1]
        )

        publisher = self.init_info["items"][0]["abstract"].split("/")[
            len(authors) - 1 : len(authors)
        ][0]

        info = soup.find(attrs={"id": "info"})
        pages = re.findall('<span class="pl">页数:</span>(.*?)<br/>', str(info))[0].strip()
        # author = soup.find_all(attrs={"class": "author"})
        price = re.findall('<span class="pl">定价:</span>(.*?)<br/>', str(info))[0].strip()
        self.bookinfo["book_name"] = book_name
        self.bookinfo["author"] = author
        self.bookinfo["publisher"] = publisher
        self.bookinfo["pages"] = pages
        self.bookinfo["price"] = price

        print(price)

        # bookinfo_dic = json.loads(info)
        # bookinfo = {
        #     "subtitle": "",
        #     "author": "",
        #     "pubdate": "",
        #     "classification": "",
        #     "publisher": "",
        #     "price": "",
        #     "pages": "",
        #     "summary": "",
        #     "img": "",
        #     "country": "",
        # }
        # if bookinfo_dic.get("code"):
        #     rstatus = "0"
        #     return rstatus, bookinfo
        # else:
        #     rstatus = "1"
        #     subtitle = bookinfo_dic["title"]
        #     author = " ".join(bookinfo_dic["author"])
        #     pubdate = bookinfo_dic["pubdate"]
        #     classification = bookinfo_dic["tags"][0]["title"]
        #     publisher = bookinfo_dic["publisher"]
        #     price = bookinfo_dic["price"]
        #     pages = bookinfo_dic["pages"]
        #     summary = bookinfo_dic["summary"]
        #     img = bookinfo_dic["images"]["small"].replace("\\", "")
        #     if author[0] == "[":
        #         country = author[1]
        #     else:
        #         country = "中"
        #     bookinfo = {
        #         "subtitle": subtitle,
        #         "author": author,
        #         "pubdate": pubdate,
        #         "classification": classification,
        #         "publisher": publisher,
        #         "price": price,
        #         "pages": pages,
        #         "summary": summary,
        #         "img": img,
        #         "country": country,
        #     }
        # return rstatus, bookinfo


if __name__ == "__main__":
    book = GetBookInfo("9787020002207")
    info = book.getbookinfo()
